package com.example.module_main.recevier

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import cn.jpush.android.api.JPushInterface
import com.alibaba.android.arouter.launcher.ARouter
import com.example.lib_common.Router
import com.example.lib_log.utils.LoggerUtils
import org.json.JSONException
import org.json.JSONObject

class MyReceiver:BroadcastReceiver() {
    companion object{
        const val TAG = "MyReceiver"
    }
    override fun onReceive(p0: Context?, p1: Intent?) {
        //数据
        val bundle = p1?.extras
        if (p1?.action == JPushInterface.ACTION_REGISTRATION_ID){//注册成功
            val registrationId = bundle?.getString(JPushInterface.EXTRA_REGISTRATION_ID)
            LoggerUtils.d(TAG,"注册成功: $registrationId")
        }else if (p1?.action == JPushInterface.ACTION_MESSAGE_RECEIVED){//透传消息
            val message = bundle?.getString(JPushInterface.EXTRA_MESSAGE)
            LoggerUtils.d(TAG,"透传消息: $message")
        }else if (p1?.action == JPushInterface.ACTION_NOTIFICATION_RECEIVED){//通知消息
            val title = bundle?.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE)
            val content = bundle?.getString(JPushInterface.EXTRA_ALERT)
            LoggerUtils.d(TAG,"通知消息 $title  $content")
        }else if (p1?.action == JPushInterface.ACTION_NOTIFICATION_OPENED){//打开通知
            val title = bundle?.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE)
            val content = bundle?.getString(JPushInterface.EXTRA_ALERT)
            LoggerUtils.d(TAG,"打开通知 $title  $content")
        }
    }
    private fun processCustomMessage(bundle: Bundle?){
        val extras = bundle?.getString(JPushInterface.EXTRA_EXTRA)
        if (TextUtils.isEmpty(extras)) {
            return
        }
        var module = ""
        var type = ""
        var param = ""
        try {
            val json = JSONObject(extras)
            val it = json.keys()
            while (it.hasNext()) {
                val myKey = it.next()
                if (myKey == "module") {
                    module = json.optString(myKey)
                }
                if (myKey == "type") {
                    type = json.optString(myKey)
                }
                if (myKey == "param") {
                    param = json.optString(myKey)
                }
            }
        } catch (e: JSONException) {
            Log.e(TAG, "Get message extra JSON error!")
        }
        when (module) {
            "2" -> ARouter.getInstance().build(Router.Ui.GoodsDetailActivity)
                .withString("param",  param)
                .navigation()
        }
    }
}